from django.shortcuts import render
from rest_framework.generics import ListAPIView
from rest_framework.views import APIView
from rest_framework.response import Response
# Create your views here.
from goods.models import *
from functools import reduce
from goods.serializer import CarouselSer, GoodsSer, CateSer
from rest_framework.pagination import PageNumberPagination


# 轮播图
class Carousel(ListAPIView):
    queryset = Carousel.objects.all()
    serializer_class = CarouselSer

# class Carousel(APIView):
#     def get(self, request):
#         # 获取所有的轮播图
#         cars = Carousel.objects.all()
#         ser = CarouselSer(cars, many=True)
#         return Response(ser.data)


class GoodsList(APIView):
    def post(self, request):
        #类别名
        name = request.data.get('categoryName')
        # 查询类别对象
        cate = Category.objects.get(cate_name=name)
        goods = cate.goods_set.all()
        goods_ser = GoodsSer(goods, many=True)
        return Response(goods_ser.data)


# 热门
class HotGoods(APIView):
    def post(self, request):
        # 前端传来的类别信息
        cate_names = request.data.get("categoryName")
        cates = [Category.objects.get(cate_name=name) for name in cate_names]
        goods = [cate.goods_set.all() for cate in cates]
        res = reduce(lambda x, y: x | y, goods).order_by('-count')
        ser = GoodsSer(res, many=True)
        return Response(ser.data)


# 获取所有的商品类别
class CateView(APIView):
    def post(self, request):
        cate = Category.objects.all()
        ser = CateSer(cate, many=True)
        return Response(ser.data)


#  根据类别id获取此类别下所有的商品
class GoodsByCateId(APIView):
    def get(self, request):
        # cate_id = request.data.get("categoryID")[0]
        cate_id = request.query_params['categoryID']
        try:
            cate = Category.objects.get(id=cate_id)
        except Exception as e:
            print(e)
            return Response({'msg': '没有此类别'})
        goods = cate.goods_set.all()
        goods_ser = GoodsSer(goods, many=True)
        return Response(goods_ser.data)


class Pagination(PageNumberPagination):
    page_size_query_param = "pageSize"
    page_query_param = "page"
    page_size = 7


# 全部商品信息
class GoodsView(ListAPIView):
    queryset = Goods.objects.all()
    serializer_class = GoodsSer
    pagination_class = Pagination
    # def post(self, request):
    #     goods = Goods.objects.all()
    #     ser = GoodsSer(goods, many=True)
    #     return Response(ser.data)
